import { useEffect, useState } from "react";
import { auth } from "@/tools/auth";

function LoginLink() {
    return (
        <ul className="nav justify-content-end">
            <li className="nav-item">
                <a className="nav-link active" aria-current="page" href="/login">登录</a>
            </li>
            <li className="nav-item">
                <a className="nav-link" href="/register">注册</a>
            </li>
        </ul>
    )
}

function ProfileLink() {

    function handleLogout(e) {
        e.preventDefault();

        try {
            auth.logout();
        } catch (error) {
            alert(error);
        }
    }

    return (
        <ul className="nav justify-content-end">
            <li className="nav-item dropdown">
                <div className="nav-link dropdown-toggle" data-bs-toggle="dropdown" role="button" aria-expanded="false">我的</div>
                <ul className="dropdown-menu dropdown-menu-end">
                    <li><a className="dropdown-item" href={`/user/${auth.currentUser && auth.currentUser.user_id}`}>主页</a></li>
                    <li><a className="dropdown-item" onClick={handleLogout}>退出</a></li>
                </ul>
            </li>
            <li className="nav-item">
                <a className="nav-link" href="/profile"></a>
            </li>
        </ul>
    )
}

export default function HomeNav() {

    const [isLogin, setIsLogin] = useState(false);

    useEffect(() => {
        auth.currentUserObservable.subscribe(currentUser => {
            if (currentUser) {
                setIsLogin(true);
            } else {
                setIsLogin(false)
            }
        })
    }, [isLogin]);

    return (
        <nav className="navbar navbar-expand-md navbar-light bg-light rounded" aria-label="Eleventh navbar example">
            <div className="container-fluid">
                <a className="navbar-brand" href="/">LookeLooke.com</a>

                {/* 下拉展开按钮 */}
                <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarsExample09" aria-controls="navbarsExample09" aria-expanded="false" aria-label="Toggle navigation">
                    <span className="navbar-toggler-icon"></span>
                </button>

                {/* 响应式下拉导航链接 */}
                <div className="collapse navbar-collapse row" id="navbarSupportedContent">
                    {isLogin ? <ProfileLink /> : <LoginLink />}
                </div>
            </div>
        </nav>
    );
}
